<template>
  <div v-if="loopCharacteristics === 'ParallelMultiInstance' || loopCharacteristics === 'SequentialMultiInstance'">
    <el-form size="small" label-width="90px" @submit.prevent>
      <template>
        <el-form-item label="完成条件" key="completionCondition">
          <el-select v-model="loopInstanceForm.completionCondition" @change="updateLoopCondition">
            <el-option
              v-for="item in completeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </template>
      <el-form-item label="过滤策略" key="completionCondition">
        <el-select v-model="loopInstanceForm.filters" @change="updateLoopBase" clearable multiple>
          <el-option
            v-for="item in filters"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { watch } from 'vue';

export default {
  name: "ElementMultiInstance",
  props: {
    businessObject: Object,
    type: String,
    id: String,
    options: Object
  },
  inject: {
    prefix: "prefix"
  },
  data() {
    return {
      loopCharacteristics: "",
      //默认配置，用来覆盖原始不存在的选项，避免报错
      defaultLoopInstanceForm: {
        collection: '${selectedUsers}',
        elementVariable: '',
        completionCondition: "",
        loopCardinality: "",
        extensionElements: [],
        filters: [],
        asyncAfter: false,
        asyncBefore: false,
        exclusive: false
      },
      loopInstanceForm: {},
      completeList: [
        {
          label: "一个即可",
          value: '${nrOfCompletedInstances/nrOfInstances > 0 || isReject=="1" || forceComplete=="1"}',
        },
        {
          label: "半数通过",
          value:
            '${nrOfCompletedInstances/nrOfInstances >= 1/2 || isReject=="1" || forceComplete=="1"}',
        },
        {
          label: "全部通过",
          value:
            '${nrOfCompletedInstances/nrOfInstances >= 1 || isReject=="1" || forceComplete=="1"}',
        },
      ],
    };
  },
  watch: {
    businessObject: {
      handler(val) {
        // 默认变量
        this.filters = this.options.filters || []
        this.defaultLoopInstanceForm.elementVariable = `${this.id}_var`;
        this.bpmnElement = window.bpmnInstances.bpmnElement;
        this.getElementLoop(this.businessObject);
      },
      immediate: true,
      deep: true
    },
  },
  mounted() {
    // 初始没有collection 和  variable 的值
    this.setDefault(this.businessObject);
  },
  methods: {
    reload() {
      this.getElementLoop(this.businessObject);
    },
    getElementLoop(businessObject) {
      if (!businessObject.loopCharacteristics) {
        this.loopCharacteristics = "Null";
        this.loopInstanceForm = {};
        return;
      }
      if (businessObject.loopCharacteristics.$type === "bpmn:StandardLoopCharacteristics") {
        this.loopCharacteristics = "StandardLoop";
        this.loopInstanceForm = {};
        return;
      }
      if (businessObject.loopCharacteristics.isSequential) {
        this.loopCharacteristics = "SequentialMultiInstance";
      } else {
        this.loopCharacteristics = "ParallelMultiInstance";
      }
      // 合并配置
      this.loopInstanceForm = {
        ...this.defaultLoopInstanceForm,
        ...businessObject.loopCharacteristics,
        ...businessObject.loopCharacteristics.$attrs,
        completionCondition: businessObject.loopCharacteristics?.completionCondition?.body ?? "",
        loopCardinality: businessObject.loopCharacteristics?.loopCardinality?.body ?? ""
      };
      // 保留当前元素 businessObject 上的 loopCharacteristics 实例
      this.multiLoopInstance = businessObject.loopCharacteristics;

      // 更新表单
      if (
        businessObject.loopCharacteristics.extensionElements &&
        businessObject.loopCharacteristics.extensionElements.values &&
        businessObject.loopCharacteristics.extensionElements.values.length
      ) {
        this.loopInstanceForm["timeCycle"] = businessObject.loopCharacteristics.extensionElements.values[0].body
      }
    },
    setDefault(businessObject) {
      if (this.loopCharacteristics == "Null") {
        return;
      }
      if (!businessObject.loopCharacteristics.collection || !businessObject.loopCharacteristics.elementVariable) {
        this.updateLoopBase()
      }
    },
    changeLoopCharacteristicsType(type) {
      // 取消多实例配置
      if (type === "Null") {
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, { loopCharacteristics: null });
        return;
      }
      // 配置循环
      if (type === "StandardLoop") {
        const loopCharacteristicsObject = window.bpmnInstances.moddle.create("bpmn:StandardLoopCharacteristics");
        window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
          loopCharacteristics: loopCharacteristicsObject
        });
        this.multiLoopInstance = null;
        return;
      }
      // 时序
      if (type === "SequentialMultiInstance") {
        this.multiLoopInstance = window.bpmnInstances.moddle.create("bpmn:MultiInstanceLoopCharacteristics", {
          isSequential: true
        });
      } else {
        this.multiLoopInstance = window.bpmnInstances.moddle.create("bpmn:MultiInstanceLoopCharacteristics");
      }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
        loopCharacteristics: this.multiLoopInstance
      });
    },
    // 循环基数
    updateLoopCardinality(cardinality) {
      let loopCardinality = null;
      if (cardinality && cardinality.length) {
        loopCardinality = window.bpmnInstances.moddle.create("bpmn:FormalExpression", { body: cardinality });
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        loopCardinality
      });
    },
    // 完成条件
    updateLoopCondition(condition) {
      let completionCondition = null;
      if (condition && condition.length) {
        completionCondition = window.bpmnInstances.moddle.create("bpmn:FormalExpression", { body: condition });
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        completionCondition
      });
    },
    // 重试周期
    updateLoopTimeCycle(timeCycle) {
      const extensionElements = window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
        values: [
          window.bpmnInstances.moddle.create(`${this.prefix}:FailedJobRetryTimeCycle`, {
            body: timeCycle
          })
        ]
      });
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        extensionElements
      });
    },
    // 直接更新的基础信息
    updateLoopBase() {
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, {
        collection: this.loopInstanceForm.collection || null,
        elementVariable: this.loopInstanceForm.elementVariable || null,
        filters: this.loopInstanceForm.filters || null,
      });
    },
    // 各异步状态
    updateLoopAsync(key) {
      const { asyncBefore, asyncAfter } = this.loopInstanceForm;
      let asyncAttr = Object.create(null);
      if (!asyncBefore && !asyncAfter) {
        this.loopInstanceForm["exclusive"] = false
        asyncAttr = { asyncBefore: false, asyncAfter: false, exclusive: false, extensionElements: null };
      } else {
        asyncAttr[key] = this.loopInstanceForm[key];
      }
      window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.multiLoopInstance, asyncAttr);
    }
  },
  beforeUnmount() {
    this.multiLoopInstance = null;
    this.bpmnElement = null;
  }
};
</script>
